package org.example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.CountDownLatch;

public class HorseRace2 {

    //    10个线程模拟赛马，所有马到达终点裁判宣布成绩
    // 使用countDownLatch
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            new Thread(new Horse("🐴" + i, finishCountDownLatch)).start();
        }
        System.out.println("准备");
        startCountDownLatch.countDown();
        finishCountDownLatch.await();
        System.out.println("结束");
//        for (int i = 0; i < result.size(); i++) {
//            System.out.println(result.get(i));
//        }
        concurrentLinkedDeque.stream().forEach(System.out::println);


    }

    private static ConcurrentLinkedDeque concurrentLinkedDeque = new ConcurrentLinkedDeque();
    private static List<String> result = Collections.synchronizedList(new ArrayList<>());
    private static CountDownLatch startCountDownLatch = new CountDownLatch(1);
    private static CountDownLatch finishCountDownLatch = new CountDownLatch(10);


    static class Horse implements Runnable {
        String name;
        CountDownLatch finishCountDownLatch;

        public Horse(String name, CountDownLatch finishCountDownLatch) {
            this.name = name;
            this.finishCountDownLatch = finishCountDownLatch;
        }

        @Override
        public void run() {
            try {
                startCountDownLatch.await();
                long time = (long) (Math.random() * 1000);
                Thread.sleep(time);
                System.out.println(name + "到达终点");

                result.add(name + "耗时" + time);
                concurrentLinkedDeque.add(name + "耗时" + time);
                finishCountDownLatch.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}
